package durst.data.json;

import java.sql.SQLException;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import com.sdicons.json.mapper.helper.SimpleMapperHelper;
import com.sdicons.json.model.JSONObject;
import com.sdicons.json.model.JSONValue;

import durst.data.Account;
import durst.data.UserCalendar;
import durst.data.dao.DaoFactory;

public class UserCalendarJSONHelper implements SimpleMapperHelper {

	@Override
	public Class<UserCalendar> getHelpedClass() {
		return UserCalendar.class;
	}
	
	@Override
	public JSONValue toJSON(Object aPojo) throws MapperException {
		if (aPojo instanceof UserCalendar && aPojo != null) {
			UserCalendar cal = (UserCalendar)aPojo;
			
			if (cal.getName() == null) {
				try {
					DaoFactory.getInstance().createDao(UserCalendar.class).refresh(cal);
				}
				catch (SQLException e) {
					throw new MapperException("could not refresh Calendar object from DB!");
				}
			}
			if (cal.getOwner().getFirstName() == null) {
				try {
					DaoFactory.getInstance().createDao(Account.class).refresh(cal.getOwner());
				}
				catch (SQLException e) {
					throw new MapperException("could not refresh Account object from DB!");
				}
			}
			
			JSONObject ret = new JSONObject();
			ret.getValue().put("id", JSONMapper.toJSON(cal.getId()));
			ret.getValue().put("name", JSONMapper.toJSON(cal.getName()));
			ret.getValue().put("shared", JSONMapper.toJSON((cal.getShared())));
			ret.getValue().put("owner", JSONMapper.toJSON((cal.getOwner().getFullName())));
			ret.getValue().put("jumplist", JSONMapper.toJSON(cal.isJumplist()));
			return ret;
		}
		
		return null;
	}

	@Override
	public Object toJava(JSONValue aValue, Class aRequestedClass) throws MapperException {
		// We won't be using this functionality
		return null;
	}
}
